﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using BookDownloader.Core.Behaviour;
using BookDownloader.Core.Data;
using BookDownloader.Core.Implementation.BaseLibEngine.Parser;
using MySql.Data.MySqlClient;

namespace BookDownloader.Core.Implementation.BaseLibEngine
{
	[Serializable]
	public class LibraryProviderBase : ILibraryListProvider
	{
		protected readonly List<Author> authors = new List<Author>();
		protected readonly List<Book> books = new List<Book>();
		protected readonly List<AuthorBook> authorBooks = new List<AuthorBook>();
		private IList<LibraryBook> list;

		public LibraryProviderBase(List<LibraryBook> library)
		{
			list = library;
		}

		public IList<LibraryBook> List
		{
			get { return list; }
		}

		public void LoadCachedList()
		{
			throw new NotImplementedException();
		}

		public void RefreshList()
		{
			LoadData();
			CompileLibrary();
		}

		protected virtual void LoadData()
		{
		}

		private void CompileLibrary()
		{
			var libraryBooks = authors.Join(authorBooks, author => author.Id, ab => ab.AuthorId, (author, ab) =>
				new { author, ab }).Join(books, x => x.ab.BookId, book => book.Id, (a, b) => new LibraryBook()
				                                                                  	{
																																							ContentId = b.Id,
																																							Author = a.author.FirstName + ' ' + a.author.LastName,
																																							FirstName = a.author.FirstName,
																																							LastName = a.author.LastName,
																																							Title = b.Title,
																																							TitleOriginal = b.TitleOriginal
				                                                                  	});
			List.Clear();
			((List<LibraryBook>)List).AddRange(libraryBooks);
		}
	}
}
